package gestoremulte.pack;

import ibz.techconsulting.posprinterdriver.api.PosPrinterUtilities;
import ibz.techconsulting.posprinterdriver.api.PrinterSettings;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.NoSuchPaddingException;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class RiassuntoMultaActivity extends Activity {

	private EditText targa;
	private EditText via_comune;
	private EditText data_ora;
	private TextView sanzione;
	private String numero_verbale;
	private Button verbale;
	private Button invia;
	private Button stampaButton;
	private boolean stampapressed;
	private Button annullaNotifica;
	
	private Button SalvaButton;
	
	private TextView nverbale;
	private ImageView im;
	private Bitmap foto;
	private boolean start;
	 private static final String SERVICE_URL ="https://91.226.109.144/GestioneMulteServer/notifica/aggiungi";
	 
	 private static final String SERVICE_URL_ANNULLA_NOTIFICA = "https://91.226.109.144/GestioneMulteServer/notifica/cancella";
	 private String LocationFile = Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Foto"+File.separator;
	 private static String LocationFileAutosave = Environment.getExternalStorageDirectory()+File.separator+"GestioneMulte"+File.separator+"Files"+ File.separator+"temp"+File.separator;
	 private static final int ENABLE_BLUETHOOT = 100;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.riassuntomulta);
        
        stampapressed = false;
        start = true;
        
        targa = (EditText) findViewById(R.id.editTargaRiassunto);
        via_comune = (EditText) findViewById(R.id.editTextViaComuneRiassunto);
        data_ora = (EditText) findViewById(R.id.dataOraEditTextRiassunto);
        sanzione = (TextView) findViewById(R.id.SanzioneEdit);
        im = (ImageView) findViewById(R.id.imageView1);
        nverbale = (TextView) findViewById(R.id.TextNVerbale);
        
        nverbale.setText(getIntent().getStringExtra("nverbale"));
        targa.setText(getIntent().getStringExtra("targa"));
        via_comune.setText(getIntent().getStringExtra("via"));
        data_ora.setText(getIntent().getStringExtra("data_ora"));
        sanzione.setText(getIntent().getDoubleExtra("sanzione", 0) + " " + "euro");
        
        numero_verbale = getIntent().getStringExtra("nverbale");
        
        verbale =(Button) findViewById(R.id.VerbaleButton);
        
        verbale.setOnClickListener(VerbaleButtonListener);
        
        invia = (Button) findViewById(R.id.InviaButton);
        invia.setOnClickListener(InviaButtonListener);
        
        annullaNotifica =  (Button) findViewById(R.id.AnnullaNotificaButton);
        annullaNotifica.setOnClickListener(AnnullaNotificaListner);
        
        stampaButton = (Button) findViewById(R.id.StampaButton);
        stampaButton.setOnClickListener(stampaButtonListner);
        
        SalvaButton = (Button) findViewById(R.id.SalvaButtonNotifica);
        SalvaButton.setOnClickListener(SalvaNotificaListner);
        
        try {
        	foto = BitmapFactory.decodeFile(LocationFile+numero_verbale+".jpg");
        	} catch (OutOfMemoryError e) {
        		Toast.makeText(this, "impossibile caricare la notifica aspettare qualche secondo", Toast.LENGTH_SHORT).show();
        	}
        
        
        if (!getIntent().getBooleanExtra("fromDB", false)){
        	if (VariabiliCondiviseApplication.fotoScattata){
        		foto = BitmapFactory.decodeFile(LocationFile+numero_verbale+".jpg"); 
            	Display display= getWindowManager().getDefaultDisplay();
            	
            	im.setImageBitmap(foto);
            	im.setAdjustViewBounds(true);
       	     	im.setMaxHeight(display.getHeight()/2);
       	     	im.setMaxWidth(display.getWidth()-100);
        	}
        	else{
        		File file = new File(LocationFile+numero_verbale+".jpg");
	    		if (file != null)
	    			file.delete();
	    		File file_temp_Notifica = new File(LocationFileAutosave + "tempNotifica");
	    		file_temp_Notifica.delete();
	    		File file_temp_Verbale = new File(LocationFileAutosave + "tempVerbale");
	    		file_temp_Verbale.delete();
        	}
        }
        else if(foto != null){
        	VariabiliCondiviseApplication.fotoScattata = true;

        	Display display= getWindowManager().getDefaultDisplay();
        	
        	im.setImageBitmap(foto);
        	im.setAdjustViewBounds(true);
   	     	im.setMaxHeight(display.getHeight()/2);
   	     	im.setMaxWidth(display.getWidth()-100);
   	     	
        }
        
        new Thread(new Runnable() {
            public void run() {
                
            	while (start){
            		try {
						Thread.sleep(15000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
            		if (!start)
            			break;
            		ArrayList <String> infraz = getIntent().getStringArrayListExtra("infraz");
    	        	ArrayList <String> cod = getIntent().getStringArrayListExtra("cod");
    	        	
    	        	Notifica nn = new Notifica(data_ora.getText().toString(), via_comune.getText().toString(),getIntent().getDoubleExtra("sanzione", 0),nverbale.getText().toString(),targa.getText().toString(),cod,infraz,"","","","" ,getIntent().getDoubleExtra("lat", 1000) ,getIntent().getDoubleExtra("lon", 1000));
            		
    	        	EncryptionDecription encr = new EncryptionDecription();
    	        	
    	        	try {
    					encr.encryptSaveNotifica(nn,true);
    				} catch (InvalidKeyException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (NoSuchAlgorithmException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (NoSuchPaddingException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} catch (IOException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    	        	Log.e("Salvato", "ok");
            	}
            }
        }).start();
        
        
	}
	
	protected void onRestart(){
    	super.onRestart();
    	if (VariabiliCondiviseApplication.restored){
    		
    		TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
            VariabiliCondiviseApplication.IMEI = telephonyManager.getDeviceId();
			VariabiliCondiviseApplication.online = false;
			
			CustomDialogLoginOffline dialog = new CustomDialogLoginOffline(this);
		    dialog.setCancelable(false);
		    dialog.show();
    	}
    	
    	
    }
	
	protected void onStart(){
    	super.onStart();
    	
    	if (VariabiliCondiviseApplication.online == false){
    		invia.setEnabled(false);
    		//stampaButton.setEnabled(false);
    		annullaNotifica.setEnabled(false);
    		
    	}
    	
    	else{
    		invia.setEnabled(true);
    		//stampaButton.setEnabled(true);
    		annullaNotifica.setEnabled(true);
    	}
    	
    	start = true;
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu2, menu);
        return true;
    }
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.icon: 
            	CustomDialogLoginOnline dialog = new CustomDialogLoginOnline(this);
            	dialog.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						if (VariabiliCondiviseApplication.online == true){
				    		invia.setEnabled(true);
				    		//stampaButton.setEnabled(true);
				    		annullaNotifica.setEnabled(true);
				    		
				    	}
						
					}
            	});

            	dialog.show();
                break;
           
        }
        return true;
    }
	
	private OnClickListener VerbaleButtonListener = new OnClickListener() {
        public void onClick(View v) {
        	
        	Intent i = new Intent(RiassuntoMultaActivity.this,VerbaleActivity.class);
        	i.putExtra("targa", targa.getText().toString());
        	i.putExtra("via", via_comune.getText().toString());
        	i.putExtra("data_ora", data_ora.getText().toString());
        	i.putExtra("nverbale", numero_verbale);
        	i.putExtra("infrazioni", getIntent().getStringExtra("infrazioni"));
        	i.putExtra("sanzione", getIntent().getDoubleExtra("sanzione", 0));
        	i.putExtra("fromDB", false);
        	i.putExtra("lat", getIntent().getDoubleExtra("lat", 1000));
        	i.putExtra("lon", getIntent().getDoubleExtra("lon", 1000));
        	startActivity(i);
        	
        	
        }
	 };
	 
	 
	 private OnClickListener InviaButtonListener = new OnClickListener() {
        public void onClick(View v) {
	      	
        	
        	
        	ArrayList <String> infraz = getIntent().getStringArrayListExtra("infraz");
        	ArrayList <String> cod = getIntent().getStringArrayListExtra("cod");
        	       	
        	Notifica notifica = null;
        	
        	if (VariabiliCondiviseApplication.fotoScattata){
        		String foto_base64;
        		
        		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                foto.compress(Bitmap.CompressFormat.JPEG, 60, baos); //foto è l'oggetto Bitmap   
                byte[] image = baos.toByteArray();

                foto_base64 = Base64.encodeToString(image,Base64.DEFAULT);
                Log.e("LUNGHEZZA",""+ foto_base64.length());

        		notifica = new Notifica(data_ora.getText().toString(), via_comune.getText().toString(),getIntent().getDoubleExtra("sanzione", 0),nverbale.getText().toString(),targa.getText().toString(),cod,infraz,foto_base64,VariabiliCondiviseApplication.matricola,VariabiliCondiviseApplication.IMEI,VariabiliCondiviseApplication.codice, getIntent().getDoubleExtra("lat", 1000) ,getIntent().getDoubleExtra("lon", 1000) );
        	}
        	else
        		notifica = new Notifica(data_ora.getText().toString(), via_comune.getText().toString(),getIntent().getDoubleExtra("sanzione", 0),nverbale.getText().toString(),targa.getText().toString(),cod,infraz,VariabiliCondiviseApplication.matricola,VariabiliCondiviseApplication.IMEI,VariabiliCondiviseApplication.codice ,getIntent().getDoubleExtra("lat", 1000) ,getIntent().getDoubleExtra("lon", 1000));
        	
        	String sampleURL = SERVICE_URL ;  	 
            WebServiceComunication wst = new WebServiceComunication(WebServiceComunication.POST_JSON_NOTIFICA, v.getContext(), "Invio notifica in corso...");   
            wst.setNotifica(notifica);          
            wst.execute(new String[] { sampleURL });
        	      	
       
        }
	 };
	 
	 private OnClickListener stampaButtonListner = new OnClickListener() {
	        public void onClick(View v) {
	        	
	        	BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	    		if (mBluetoothAdapter == null) {
	    			Toast.makeText(v.getContext(), "Questo dispositivo non supporta il bluethoot", Toast.LENGTH_SHORT).show();
	    		}
	    		
	    		else{
	    			if (!mBluetoothAdapter.isEnabled()) {
	    			    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
	    			    startActivityForResult(enableBtIntent, ENABLE_BLUETHOOT);
	    			    
	    			}
	    			
	    			else{
	    				ArrayList <String> infraz = getIntent().getStringArrayListExtra("infraz");
			        	ArrayList <String> cod = getIntent().getStringArrayListExtra("cod");
			        	Notifica notifica = new Notifica(data_ora.getText().toString(), via_comune.getText().toString(),getIntent().getDoubleExtra("sanzione", 0),nverbale.getText().toString(),targa.getText().toString(),cod,infraz,VariabiliCondiviseApplication.matricola,VariabiliCondiviseApplication.IMEI,VariabiliCondiviseApplication.codice ,getIntent().getDoubleExtra("lat", 1000) ,getIntent().getDoubleExtra("lon", 1000));
			        	
			        	stampapressed = true;
			        	
			        	Printer printer = new Printer(v.getContext());
			        	printer.printNotifica(notifica);
	    			}
	    		}
	        	
	        
	        }
		 };
		 
	 public void setNumeroVerbale(String s){
		 this.numero_verbale = s;
	 }
 
	 private OnClickListener AnnullaNotificaListner = new OnClickListener() {
	        public void onClick(View v) {
	        	
	        	WebServiceSyncComunication com = new WebServiceSyncComunication(SERVICE_URL_ANNULLA_NOTIFICA,WebServiceSyncComunication.ANNULLA_NOTIFICA, v.getContext());
	    		com.setnVerbaleAnnullaNotifica(getIntent().getStringExtra("nverbale"));
	        	com.Comunicazione();
	    		boolean esitoComunicazione = com.isEsitoComunicazione();
	
	            if (esitoComunicazione){
	            	 MyDatabase db=new MyDatabase(v.getContext());
	            	 db.open();
	 	             db.updateNVerbale(getIntent().getStringExtra("nverbale"),0);
	 	             db.close();
	             }
	        }
		 };
		 
	 private OnClickListener SalvaNotificaListner = new OnClickListener() {
	        public void onClick(View v) {
	        	
	        	ArrayList <String> infraz = getIntent().getStringArrayListExtra("infraz");
	        	ArrayList <String> cod = getIntent().getStringArrayListExtra("cod");
	        	
	        	Notifica nn = new Notifica(data_ora.getText().toString(), via_comune.getText().toString(),getIntent().getDoubleExtra("sanzione", 0),nverbale.getText().toString(),targa.getText().toString(),cod,infraz,"","","","" ,getIntent().getDoubleExtra("lat", 1000) ,getIntent().getDoubleExtra("lon", 1000));
	        	MyDatabase db=new MyDatabase(v.getContext());
	        	db.open();
	        	db.insertNotifica(nn);
	        	db.updateNVerbale(nverbale.getText().toString(),1);
	        	db.close();
	        	 
	        	ElementoLista el = new ElementoLista(nn.getVerbaleNumber(),nn.getData_ora(),"Notifica");
	        	WriteReadElementoLista nuovoElemento = new WriteReadElementoLista();
	        	nuovoElemento.writeElemento(el);
	        	
	        	EncryptionDecription encr = new EncryptionDecription();
	        	
	        	try {
					encr.encryptSaveNotifica(nn,false);
				} catch (InvalidKeyException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchAlgorithmException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchPaddingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	
	        }
		 };	 
		 
		 protected void onPause(){
		    	super.onPause();
		    	if (VariabiliCondiviseApplication.backClick || stampapressed)
		    		VariabiliCondiviseApplication.restored = false;
		    	else
		    		VariabiliCondiviseApplication.restored = true;
		    	VariabiliCondiviseApplication.backClick = false;
		    	stampapressed = false;
		    	start = false;
		    	
		    }
		 
		 @Override
		    public void onBackPressed() {
			 	super.onBackPressed();
		    	VariabiliCondiviseApplication.backClick = true;
		    	
		    }
		 
	     @Override
		 protected void onActivityResult (int requestCode, int resultCode, Intent data){
			 
			 if (requestCode == ENABLE_BLUETHOOT){
				 if (resultCode == RESULT_OK ){
					 ArrayList <String> infraz = getIntent().getStringArrayListExtra("infraz");
			        	ArrayList <String> cod = getIntent().getStringArrayListExtra("cod");
			        	Notifica notifica = new Notifica(data_ora.getText().toString(), via_comune.getText().toString(),getIntent().getDoubleExtra("sanzione", 0),nverbale.getText().toString(),targa.getText().toString(),cod,infraz,VariabiliCondiviseApplication.matricola,VariabiliCondiviseApplication.IMEI,VariabiliCondiviseApplication.codice ,getIntent().getDoubleExtra("lat", 1000) ,getIntent().getDoubleExtra("lon", 1000));
			        	
			        	stampapressed = true;
			        	
			        	Printer printer = new Printer(this);
			        	printer.printNotifica(notifica);
				 }
				 else
					 Toast.makeText(this.getApplicationContext(), "Deve essere attivato il bluethoot per accedere a questa funzionalità", Toast.LENGTH_SHORT).show();
				 
			 }
			 
		 }
	 
}
